package com.hhxy.handler.security;

import com.alibaba.fastjson.JSON;
import com.hhxy.utils.WebUtils;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ghp
 * @date 2023/3/9
 * @title
 * @description 用于处理已经进行了身份验证但不具有访问受保护资源所需权限的用户的情况
 */
@Slf4j
@Component
public class AccessDeniedImplHandler implements AccessDeniedHandler {

    /**
     * 处理权限不足时的异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.error("权限不足, 异常信息：{}", e.getMessage());
        // 响应式给前端，告诉它权限不足
        ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_UNPOWER_ERROR);
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
